package com.yhy.common.utils;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;
import java.util.List;

/**
 * json字符与对像转换
 * Created by yanghuiyuan on 2017/11/20.
 */
public final class JsonUtils {

    //public static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 使用泛型方法，把json字符串转换为相应的JavaBean对象。
     * (1)转换为普通JavaBean：readValue(json,Student.class)
     * (2)转换为List,如List<Student>,将第二个参数传递为Student
     * [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
     *
     * @param jsonStr
     * @param valueType
     * @return
     */
    public static <T> T fromJson(String jsonStr, Class<T> valueType) {
        try {
            if (StringUtils.isBlank(jsonStr)) {
                return null;
            }
            return JSON.parseObject(jsonStr, valueType);//.readValue(jsonStr, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * json数组转List
     * @param jsonStr
     * @param valueTypeRef
     * @return
     */
   /* public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
        try {
            return objectMapper.readValue(jsonStr, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    /**
     * 把JavaBean转换为json字符串
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        try {
            return JSON.toJSONString(object);
            //return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T tranObject(Object sourceObj, Class<T> valueType) {
        if(sourceObj == null) {
            return null;
        }
        return fromJson(toJson(sourceObj), valueType);
    }


    public static <T> List<T> tranList(Collection sourceList, Class<T> valueType) {
        List<T> destinationList = Lists.newArrayList();
        sourceList.stream().forEach(sourceObject -> {
            T destinationObject = tranObject(sourceObject, valueType);
            destinationList.add(destinationObject);
        });
        return destinationList;
    }

}